/*
 **********************************************************************************
 * Copyright www.ebidding.com.cn 2017年09月07日 Authors: 符强年 <fqn@ebidding.com.cn>*
 **********************************************************************************
 */
package com.example.demo.common.msg;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.example.demo.common.exception.EbsException;
import com.example.demo.common.msg.vo.*;
import com.example.demo.common.persistence.dao.MemUserMapper;
import com.example.demo.common.persistence.dao.MsgNodeMapper;
import com.example.demo.common.persistence.dao.MsgRecordMapper;
import com.example.demo.common.persistence.dao.MsgTemplateMapper;
import com.example.demo.common.persistence.model.MemUser;
import com.example.demo.common.persistence.model.MsgNode;
import com.example.demo.common.persistence.model.MsgTemplate;
import com.example.demo.core.util.UserUtil;
import com.example.demo.core.util.WebUtil;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

import static com.example.demo.common.msg.vo.MessageType.SMS;


/**
 * 作者: 符强年
 * 创建时间: 2017年09月07日
 * 功能描述:
 * 版本: 1.0.0
 */
@Component
@ConditionalOnProperty(prefix = "guns", name = " mq-open", havingValue = "true")
public class DefaultSendMessageService extends AbstractSendMessage {

    private Logger logger = LoggerFactory.getLogger(DefaultSendMessageService.class);


    @Autowired
    MsgRecordMapper msgRecordMapper;

    @Autowired
    MsgTemplateMapper msgTemplateMapper;

    @Autowired
    MsgNodeMapper msgNodeMapper;

    @Autowired
    private MemUserMapper userMapper;


    Map<MessageType, MessageEntitySendHandler> handlerMap = new HashMap<>();

    @Autowired
    MessageSender messageSender;


    @Override
    protected MessageSender getMessageSender() {
        return messageSender;
    }

    @Override
    protected void compose(Map<MessageType, MessageWrapper> msgMap, MessageVo messageVo) {

        //过滤用户
        Set<EbsMessageReceiver> receivers = messageVo.getReceivers();
        receivers.forEach(r -> {
            if (r != null && r.getUserId() != null) {
                MemUser user = userMapper.selectById(r.getUserId());

                String mobile = r.getMobile();
                if (StringUtils.isEmpty(mobile) && user != null) {
                    mobile = user.getMobile();
                }
                r.setMobile(mobile);
                String email = r.getEmail();
                if (StringUtils.isEmpty(email) && user != null) {
                    email = user.getEmail();
                }
                r.setEmail(email);
            }
        });

        //填充消息实体,将messageVo，MsgTemplate中的数据组合到messageWrapper
        for (Map.Entry<MessageType, MessageWrapper> entry : msgMap.entrySet()) {
            MessageType type = entry.getKey();
            MessageWrapper mw = entry.getValue();
            if (mw == null || mw.getMsgTemplate() == null) continue;

            MsgTemplate msgTemplate = mw.getMsgTemplate();
            String titleTmpl = msgTemplate.getTitle();
            String contentTmpl = msgTemplate.getContent();
            Map<String,String> dataModel  = messageVo.getAttrs();
            String content = "",title = "";
            if (StringUtils.isNotEmpty(titleTmpl)) {
                title = StringEscapeUtils.unescapeHtml(WebUtil.replaceString(titleTmpl, dataModel));
            }

            if (StringUtils.isNotEmpty(contentTmpl)) {
                content = WebUtil.replaceString(contentTmpl, dataModel);
            }

            mw.setContent(content);
            mw.setTitle(title);
            mw.setAccessToken(messageVo.getAccessToken());


            //过滤用户设置
            Set<EbsMessageReceiver> typedReceivers =
                    receivers.stream()
                            .filter((r) -> receiverFilter(r, type))
                            .collect(Collectors.toSet());

            mw.setReceivers(typedReceivers);
            mw.setSenderOrgId(UserUtil.getOrgId(messageVo.getAccessToken()));
            mw.setSenderUserId(UserUtil.getUserId(messageVo.getAccessToken()));
            mw.setBusinessCode(messageVo.getBusinessCode());
            mw.setBusinessId(messageVo.getBusinessId());
            mw.setTodoUrl(messageVo.getTodoUrl());
        }
    }


    /**
     * 过滤用户配置，是否愿意接受消息，（注意代办和消息不允许取消订阅)
     *
     * @param receiver
     * @param messageType
     * @return
     */
    @Override
    protected boolean receiverFilter(EbsMessageReceiver receiver, MessageType messageType) {

        boolean state = true;

        return state;
    }


    /**
     * 根据模板节点编码，模板类型获取节点模板
     *
     * @param nodeCode
     * @param messageTypes
     * @return
     */
    @Override
    protected Map<MessageType, MessageWrapper> fetchMessageTemplate(String nodeCode, List<MessageType> messageTypes) {

        Wrapper entityWrapper = new EntityWrapper();
        entityWrapper.eq("code",nodeCode);
        MsgNode msgNode = (MsgNode)msgNodeMapper.selectList(entityWrapper).get(0);

        if(msgNode == null){
            throw new EbsException("common_msg_node_not_found",nodeCode);
        }

        String msgTypes = messageTypes.stream().map((messageType) -> messageType.stringValue()).collect(Collectors.joining(","));

        entityWrapper.in("msg_type",msgTypes);
        List<MsgTemplate> msgTemplates = msgTemplateMapper.selectList(entityWrapper);

        Map<MessageType, MessageWrapper> result =
                msgTemplates.stream().collect(Collectors.toMap(mt -> MessageType.instanceOf(mt.getMsgType()),
                        mt -> {
                            MessageWrapper r = new MessageWrapper(mt);
                            r.setMessageNodeName(msgNode.getName());
                            r.setMessageNodeCode(msgNode.getCode());
                            return r;
                        }, (k1, k2) -> k1));
        /*
        messageTypes.forEach(msgType ->{

        });*/
        return result;
    }

    /**
     * 根据 企业（orgId）模板节点（messageNodeCode），检查
     *
     * @param accessToken
     * @param messageCode
     * @return
     */
    @Override
    protected MessageCheckResult check(String accessToken, String messageCode) {

        MessageCheckResult result = new MessageCheckResult();
        result.setNeedSend(true);
        result.setMessageTypes(Arrays.asList(MessageType.EMAIL, MessageType.SITE, MessageType.TODO, SMS));
        if (StringUtils.isEmpty(accessToken)) {
            return result;
        }
        Integer orgId = UserUtil.getOrgId(accessToken);
        //todo 根据企业消息节点设置，返回该业务节点需要发送的消息类型∏∏∏

        return result;
    }


}
